﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.Core;
using EfSearchModel.Model;
using QuickApp.MVCControl;
using Resto.CostControl.Core;
using QuickApp.MVCControl.Form;
using System.Data.Entity;
using System.Data.SqlClient;

namespace Resto.CostControl.Web.Controllers
{
    public class MaterialProcessController : Controller
    {
        private readonly IRepository<MaterialProcess> _Repo;
        private readonly IRepository<MaterialProcessItem> _RepoItem;
        private readonly IRepository<Material> _RepoMaterial;
        private readonly IUnitOfWork _UnitOfWork;

        public MaterialProcessController(IRepository<MaterialProcess> repo, IRepository<MaterialProcessItem> repoItem, IRepository<Material> RepoMaterial, UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _RepoItem = repoItem;
            _RepoMaterial = RepoMaterial;
            _UnitOfWork = unitOfWork;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            //where.AddItem("OrderState", "caogao");
            var list = _Repo.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<MaterialProcess>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult Edit(string Id, string category, string date)
        {
            MaterialProcess data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = _Repo.Find(Id);
            }
            else
            {
                data = new MaterialProcess();
                data.Id = Guid.NewGuid().ToString();
                data.OrderState = "Draft";
                if (!string.IsNullOrEmpty(category))
                {
                    data.Category = ViewBag.Category = category;
                    ViewBag.Date = date;
                    data.ProcessDate = DateTime.Parse(date);
                }
                else
                {
                    data.ProcessDate = DateTime.Now;
                }
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(MaterialProcess data, IList<MaterialProcessItem> MaterialList)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (ModelState.IsValid)
            {
                try
                {
                    var ItemDesc = "";
                    if (MaterialList != null)
                    {
                        _RepoItem.DeleteAll(m => m.OrderId == data.Id);
                        foreach (var m in MaterialList)
                        {
                            m.OrderId = data.Id;
                            m.MaterialId = m.MaterialId ?? m.Id;
                            m.Id = Guid.NewGuid().ToString();
                            m.State = "Draft";
                            //单位换算（斤=>克）
                            m.ProcessCount = m.ProcessCount * 500;
                            m.ExpectedPickCount = m.ExpectedPickCount * 500;
                            m.ActualPickCount = m.ActualPickCount * 500;
                            m.ActualStorageCount = m.ActualStorageCount * 500;
                            m.ExpectedStorageCount = m.ExpectedStorageCount * 500;
                            // 处理期望领料数
                            var Material = _RepoMaterial.Find(m.MaterialId);
                            if (Material != null)
                            {
                                m.ExpectedPickCount = m.ProcessCount * Material.ProcessRate;
                            }
                            
                            _RepoItem.Insert(m);
                            ItemDesc += m.Name + "，";
                        }
                    }
                    if (_Repo.Find(data.Id) == null)
                    {
                        _Repo.Insert(data);
                        data.ItemDesc = ItemDesc.Trim('，');
                    }
                    else
                    {
                        data = _Repo.Find(data.Id);
                        data.ItemDesc = ItemDesc.Trim('，');
                        TryUpdateModel(data);
                    }

                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch (Exception ex)
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败：" + ex.Message;
                }
            }

            return Json(msg);
        }

        [HttpPost]
        public JsonResult Delete(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    _Repo.Delete(id);
                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败，请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }
        [HttpPost]
        public JsonResult MaterialList(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<MaterialProcessItem>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult EditList()
        {
            return View();
        }

        [Ninject.Inject]
        public DbContext context { get; set; }

        [HttpPost]
        public JsonResult EditList(string parentId, string category, DateTime? date, DWZPageInfo pageInfo, DWZQueryModel where)
        {
            // 从加工计划中产生明细
            if (!string.IsNullOrEmpty(category))
            {
                string sql = @"select '' as OrderId, '' as RawMaterialName, Id as MaterialId, PurchaseWeight as ProcessCount
                            , 0.0 as ExpectedPickCount, 0.0 as ActualPickCount, 0.0 as ActualStorageCount
                            , PurchaseWeight as ExpectedStorageCount
                            ,'Draft' as State,* from dbo.V_MaterialProcessPlan
                            where date = @Date and category = @Category";

                List<SqlParameter> plist = new List<SqlParameter>();
                plist.Add(new SqlParameter("@Date", date.Value));
                plist.Add(new SqlParameter("@Category", category));

                var list = context.Database.SqlQuery<MaterialProcessItem>(sql, plist.ToArray()).ToList();
                foreach (var item in list)
                {
                    item.ProcessCount = item.ProcessCount / 500;
                    item.ExpectedPickCount = item.ExpectedPickCount / 500;
                    item.ActualPickCount = item.ActualPickCount / 500;
                    item.ActualStorageCount = item.ActualStorageCount / 500;
                    item.ExpectedStorageCount = item.ExpectedStorageCount / 500;
                }
                var fdata = pageInfo.ToFlexiGridData<MaterialProcessItem>(list, list.Count);
                return Json(fdata);
            }
            else
            {
                where.AddItem("OrderId", parentId == "" ? null : parentId);
                var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
                var pageList = list.Page.ToList();
                foreach (var item in pageList)
                {
                    item.ProcessCount = item.ProcessCount / 500;
                    item.ExpectedPickCount = item.ExpectedPickCount / 500;
                    item.ActualPickCount = item.ActualPickCount / 500;
                    item.ActualStorageCount = item.ActualStorageCount / 500;
                    item.ExpectedStorageCount = item.ExpectedStorageCount / 500;
                }
                var fdata = pageInfo.ToFlexiGridData<MaterialProcessItem>(list.Page.ToList(), list.Total);
                return Json(fdata);
            }
        }

        [HttpPost]
        public JsonResult DeleteItem(string Id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(Id))
            {
                try
                {
                    _RepoItem.Delete(Id);
                    _UnitOfWork.Commit();

                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }
    }
}